package com.atguigu.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.search.config.GulimallESConfig;
import com.atguigu.search.constant.EsConstant;
import com.atguigu.search.feign.ProductFeignService;
import com.atguigu.search.service.MallSearchService;
import com.atguigu.search.vo.AttrRsponseVo;
import com.atguigu.search.vo.SearchParam;
import com.atguigu.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        SearchResult result=null;
        //准备索引请求
        SearchRequest searchRequest =buildSearchRequest(param);
        try {
            //执行索引
            SearchResponse response = client.search(searchRequest, GulimallESConfig.COMMON_OPTIONS);
            //分析索引结果
            result=buildSearchResult(response,param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private SearchResult buildSearchResult(SearchResponse response,SearchParam param) {
        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();
//        设置产品信息
//        result.setProducts();
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits()!=null && hits.getHits().length>0) {
            SearchHit[] hitsHits = hits.getHits();
            for (SearchHit hit : hitsHits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //设置高亮
                if (!StringUtils.isEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                skuEsModels.add(skuEsModel);
            }
        }
        result.setProducts(skuEsModels);
//        result.setBrands();
            List<SearchResult.BrandVo> brandVos=new ArrayList<>();
            //获取到brandId_agg的聚合
            ParsedLongTerms brandId_agg = response.getAggregations().get("brandId_agg");
            List<? extends Terms.Bucket> brandBuckets = brandId_agg.getBuckets();
            for (Terms.Bucket bucket : brandBuckets) {
                SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
                String keyAsString = bucket.getKeyAsString();
                long brandId = Long.parseLong(keyAsString);
                ParsedStringTerms brandId_name_agg = bucket.getAggregations().get("brandId_name_agg");
                String brandName = brandId_name_agg.getBuckets().get(0).getKeyAsString();
                ParsedStringTerms brandId_img_agg = bucket.getAggregations().get("brandId_img_agg");
                String brandImg = brandId_img_agg.getBuckets().get(0).getKeyAsString();
                brandVo.setBrandId(brandId);
                brandVo.setBrandName(brandName);
                brandVo.setBrandImg(brandImg);
                brandVos.add(brandVo);
            }
            result.setBrands(brandVos);

//        result.setAttrs();
        List<SearchResult.AttrVo> attrVos=new ArrayList<>();
        ParsedNested attrs_agg = response.getAggregations().get("attrs_agg");
        ParsedLongTerms attrs_id_agg = attrs_agg.getAggregations().get("attrs_id_agg");
        List<? extends Terms.Bucket> attrBuckets = attrs_id_agg.getBuckets();
        for (Terms.Bucket bucket : attrBuckets) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();

            String keyAsString = bucket.getKeyAsString();
            long attrId = Long.parseLong(keyAsString);
            ParsedStringTerms attrs_name_agg = bucket.getAggregations().get("attrs_name_agg");
            String attrName = attrs_name_agg.getBuckets().get(0).getKeyAsString();

            ParsedStringTerms attrs_value_agg = bucket.getAggregations().get("attrs_value_agg");
            List<String> attrValues = attrs_value_agg.getBuckets().stream().map(item -> {
                String attrValue = item.getKeyAsString();
                return attrValue;
            }).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);

            attrVos.add(attrVo);
        }

        result.setAttrs(attrVos);
//        result.setCatelogs();
        ParsedLongTerms catelogId_agg = response.getAggregations().get("catelogId_agg");
        List<SearchResult.CatelogVo> catelogVos=new ArrayList<>();
        List<? extends Terms.Bucket> catelogBuckets = catelogId_agg.getBuckets();
        for (Terms.Bucket bucket : catelogBuckets) {
            SearchResult.CatelogVo catelogVo = new SearchResult.CatelogVo();
            String keyAsString = bucket.getKeyAsString();
            long catelogId = Long.parseLong(keyAsString);
            ParsedStringTerms catelogId_name_agg = bucket.getAggregations().get("catelogId_name_agg");
            String catelogName = catelogId_name_agg.getBuckets().get(0).getKeyAsString();
            catelogVo.setCatalogId(catelogId);
            catelogVo.setCatalogName(catelogName);
            catelogVos.add(catelogVo);
        }

        result.setCatelogs(catelogVos);

        long total=hits.getTotalHits().value;
        result.setTotal(total);
        result.setPageNum(param.getPageNum());
        int totalPages=(int)total%EsConstant.PRODUCT_PAGESIZE==0?(int)total/EsConstant.PRODUCT_PAGESIZE:((int)total/EsConstant.PRODUCT_PAGESIZE+1);
        result.setTotalPages(totalPages);
        List<Integer> pageNavs=new ArrayList<>();
        for (int i = 1; i <=totalPages ; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        if (param.getAttrs()!=null && param.getAttrs().size()>0){
            List<SearchResult.NavsVo> navsVos=param.getAttrs().stream().map(attr->{
                SearchResult.NavsVo navsVo = new SearchResult.NavsVo();
                String[] s = attr.split("_");
                navsVo.setNavsValue(s[1]);
                String attrId=s[0];

                R attrInfo = productFeignService.info(Long.parseLong(attrId));
                result.getAttrIds().add(Long.parseLong(attrId));
                if (attrInfo.getCode()==0){

                    AttrRsponseVo attrRsponseVo = attrInfo.getData("attr", new TypeReference<AttrRsponseVo>() {
                    });
                    String attrName = attrRsponseVo.getAttrName();
                    navsVo.setNavsName(attrName);
                }
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.getLink().replace("&attrs=" + encode, "").replace("attrs=" + encode+"&", "").replace("attrs=" + encode, "");
                navsVo.setLink("http://search.gulimall.com/list.html?"+replace);


                return navsVo;
            }).collect(Collectors.toList());

            result.setNavs(navsVos);
        }



        return result;
    }

    private SearchRequest buildSearchRequest(SearchParam param) {
//        构建DSL语句
        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
        /**
         * 模糊匹配、过滤（按照属性、分类、品牌、价格区间、库存）
         */
//        1、构建bool-query
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//        1.1构建must 模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
//        1.2 bool-filter过滤 分类
        if (param.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
//        1.2 bool filter 品牌
        if (param.getBrandId()!=null && param.getBrandId().size()>0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }
//        1.2 bool filter 属性
        if (param.getAttrs()!=null && param.getAttrs().size()>0){
            List<String> attrs = param.getAttrs();
            for (String attr : attrs) {
//                attrs=16_lcd
                BoolQueryBuilder attrBoolQuery = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId=s[0];
                String[] attrValues = s[1].split(":");

                attrBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                attrBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", attrBoolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            }
        }
//        1.2 bool filter 库存
        if (param.getHasStock()!=null){

            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",param.getHasStock()==1));
        }
//        1.2 bool filter 价格区间
        if (!StringUtils.isEmpty(param.getSkuPrice())){
            String[] s = param.getSkuPrice().split("_");
            if (s.length==2){
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("skuPrice").gte(s[0]).lte(s[1]));
            }else if (s.length==1){
                if (param.getSkuPrice().startsWith("_")){
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("skuPrice").lte(s[0]));
                }else if (param.getSkuPrice().endsWith("_")){
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("skuPrice").gte(s[0]));
                }
            }
        }
//        封装模糊查询条件
        sourceBuilder.query(boolQueryBuilder);

        /**
         * 排序、分页、高亮
         */
        //2 排序
        if (!StringUtils.isEmpty(param.getSort())){
            String[] s = param.getSort().split("_");
            sourceBuilder.sort(s[0], SortOrder.fromString(s[1]));
        }
        //3 分页
        sourceBuilder.from((param.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //4 高亮
        if (!StringUtils.isEmpty(param.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }
        /**
         * 聚合分析 brandId_agg  catelogId_agg  attrs_agg
         */
        /*brandId_agg*/
        TermsAggregationBuilder brandId_agg = AggregationBuilders.terms("brandId_agg").field("brandId").size(10);
        //brandId_name_agg
        TermsAggregationBuilder brandId_name_agg = AggregationBuilders.terms("brandId_name_agg").field("brandName").size(1);
        brandId_agg.subAggregation(brandId_name_agg);
//        brandId_img_agg
        TermsAggregationBuilder brandId_img_agg = AggregationBuilders.terms("brandId_img_agg").field("brandImg").size(1);
        brandId_agg.subAggregation(brandId_img_agg);
        sourceBuilder.aggregation(brandId_agg);
        /*catelogId_agg*/
        TermsAggregationBuilder catelogId_agg = AggregationBuilders.terms("catelogId_agg").field("catalogId").size(50);
//        catelogId_name_agg
        TermsAggregationBuilder catelogId_name_agg = AggregationBuilders.terms("catelogId_name_agg").field("catalogName").size(10);
        catelogId_agg.subAggregation(catelogId_name_agg);
        sourceBuilder.aggregation(catelogId_agg);
        /*attrs_agg*/
        NestedAggregationBuilder attrs_agg = AggregationBuilders.nested("attrs_agg", "attrs");
//        attrs_id_agg
        TermsAggregationBuilder attrs_id_agg = AggregationBuilders.terms("attrs_id_agg").field("attrs.attrId").size(10);
        TermsAggregationBuilder attrs_name_agg = AggregationBuilders.terms("attrs_name_agg").field("attrs.attrName");
        attrs_id_agg.subAggregation(attrs_name_agg);
        TermsAggregationBuilder attrs_value_agg = AggregationBuilders.terms("attrs_value_agg").field("attrs.attrValue");
        attrs_id_agg.subAggregation(attrs_value_agg);
        attrs_agg.subAggregation(attrs_id_agg);
        sourceBuilder.aggregation(attrs_agg);


        System.out.println("DSL语句为："+sourceBuilder.toString());

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);


        return searchRequest;
    }
}
